import { Page } from '/utils/ix' // 添加这行
import { ajax2 , ajax} from '../../ajax';


Page({
  data: {
    personList: [],
    // 输入金额
    hasTotal: 0,
    token: '',
    room: ''
  },
  facepay() {
    my.removeStorageSync({
      key: 'personInfoList'
    });
    my.redirectTo({
      url: '/pages/index/index'
    });
  },
  // 键盘监听
  onKeyPress(r) {
    switch (r.keyCode) {
      case 131:
        r.keyName = '收款';
        this.setData({ hasTotal: r.amount })
        break;
      case 132:
        r.keyName = '刷脸';
        console.log('刷脸')
        break;
      case 133:
        r.keyName = '取消';
        console.log('取消')
        break;
      case 134:
        r.keyName = '设置';
        console.log('设置')
        break;
    }
    console.log('KeyEvent', r);
  },
  onLoad(option) {
    // console.log(option)
    // 商户未登录，跳转登录页
    let that = this;
    let token = my.getStorageSync({ key: 'token' }).data;
    let room = my.getStorageSync({ key: 'room' }).data
    // console.log('room----->>>',room)
    // 设置token过期，测试用
    // let token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vcGF5LnRpYXplLmNvbS9hcGkvbWVyY2hhbnQvbG9naW4iLCJpYXQiOjE1NTIwMDczNzQsImV4cCI6MTU1MjYxMjE3NCwibmJmIjoxNTUyMDA3Mzc0LCJqdGkiOiJlNjExNDI4MjUwODEzOWE0MjlhYTg2NDc3ZGMxNGZkNCIsInN1YiI6eyJpZCI6MTIsIm5hbWUiOiJcdTU5MjlcdTYyZTlcdTRmZTFcdTRlMGFcdTYyODBcdTY3MmZcdTkwZTgiLCJwaG9uZSI6IjE3NTAwMDAxODAwIiwidHlwZSI6Im1lcmNoYW50IiwibWVyY2hhbnRfdHlwZSI6MCwicGlkIjowLCJpbWVpIjpudWxsfX0.g3Dy2qNiK1EA5cT1_ht0wAdwVBoA0VbxHR2kb0cePtk';
    if (token) {
      that.setData({ token, room })
    } else {
      my.reLaunch({ url: '../login/login' })
    }
  },
  onShow() {
    let that = this;
    that.data.personList = my.getStorageSync({ key: 'personInfoList' }).data;
    console.log('重新加载页%%%%%%%%%%%%%%%%')
    my.ix.speech({
      text: '请输入金额',
    });
  },
  fillZero(n) {
    let result = (n).toString().length === 1 ? ('0' + n): n;
    return result;
  },
  formatTime (t = new Date()) {
    let d = new Date(t);
    let year = d.getFullYear();
    let month = d.getMonth() + 1;
    let date = d.getDate();
    let hours = d.getHours();
    let minutes = d.getMinutes();
    let seconds = d.getSeconds();
    // let result = `${year}-${this.fillZero(month)}-${this.fillZero(date)} ${this.fillZero(hours)}:${this.fillZero(minutes)}:${this.fillZero(seconds)}`;
    let M = this.fillZero(hours) * 3600  + (this.fillZero(minutes) * 60 ) + (this.fillZero(seconds) * 1)
    // console.log(M)
    let result = `${year + this.fillZero(month) + this.fillZero(date)}` + M
    return result;
  },
  facepay() {
    let num = this.formatTime()
    let math = parseInt( (Math.random() + 1) * 10000000 )
    // 生成订单
    var bizNo = 'ms' + num + math
    console.log(num,math,bizNo)
    my.ix.startApp({
      appName: 'cashier',
      bizNo: bizNo,
      totalAmount: this.data.hasTotal,
      orderDetail: [{ name: '支付', content: '普通商品' }],
      posTimeout: '30',
      faceLoadingTimeout: '10',
      scanLoadingTimeout: '10',
      success: async (r) => {
        console.log(r)
        // my.showToast({ content: r.barCode });
        let parameData = {
          auth_code: r.barCode,
          token: this.data.token,
          out_trade_no: bizNo,
          amount: this.data.hasTotal,
          remark: this.data.room
        }
        console.log(parameData)
        //支付接口
        let payResultData = await ajax("/faceScanPayment", parameData, 'POST');
        if (payResultData.data.code === 10000) { 
          console.log('success---->>>>',payResultData.data.code)
          my.reLaunch({url:'/pages/index/index'});

        }

        console.log(payResultData)
      },
      fail: (r) => {
        my.showToast({ content: JSON.stringify(r) });
      }
  });
  },
  // 普通支付
  async facePay1(touchStyle) {
    let totalAmount = this.data.totalAmount;
    // 支付金额清0，否则按下支付btn会直接调起收银台，因为有原来的this.data.totalAmount
    this.setData({ totalAmount: 0 })
    if (totalAmount > 0 && touchStyle === 2 && this.data.token) {
      console.log('创建订单')
      //创建订单
      let createOrderData = await ajax("/SmallAppSmilePreform", { token: this.data.token, amount: totalAmount }, 'POST');
      console.log(createOrderData);
      if (createOrderData.data.status === 1) {
        console.log('进来了');
        this.setData({ out_trade_no: createOrderData.data.out_trade_no });
        //启动收银台
        my.ix.startApp({
          appName: 'cashier',
          bizNo: createOrderData.data.out_trade_no,
          totalAmount: totalAmount,
          orderDetail: [{ name: '支付', content: '普通商品' }],
          showScanPayResult: false,
          success: async (r) => {
            let parameData = {
              code: r.barCode,
              token: this.data.token,
              out_trade_no: this.data.out_trade_no,
              devices: my.getStorageSync({ key: 'system' }).data,
              ftoken: r.ftoken
            }
            console.log(parameData)
            //支付接口
            let payResultData = await ajax("/SmallAppSmilePay", parameData, 'POST');
            console.log(payResultData)
            //暂时关闭自定义结果页
            // my.navigateTo({url: '../pay-result/pay-result?out_trade_no='+ this.data.out_trade_no + '&result_status=1'});
            if (payResultData.data.status === 1) {
              console.log('支付成功了。。。')
              // 支付成功后给后屏发送支付成功信息
              my.ix.sendBuddyMessage({
                target: "2019120369640398",
                data: {
                  pay_status: true,
                },
                success: (res) => {
                  console.log('发送成功', res)
                },
                fail: (res) => { }
              })
              // 请求打印数据并打印
              this.getData()
              // this.onKeyPress(r)
              my.ix.startApp({
                appName: 'scanPayResult',
                bizNo: this.data.out_trade_no,
                totalAmount: totalAmount,
                success: (r) => {
                  console.log('展示结果页')
                }
              })
            }
          }
        })
      }
    } else {
      my.ix.speech({
        text: '请输入金额',
        success: (r) => {
          console.log('请输入金额')
        }
      });
    }
    console.log('aaa')
  },

  // 押金扫码支付
  async fundauthPay(touchStyle) {
    let totalAmount = this.data.totalAmount;
    this.setData({ totalAmount: 0 })
    if (totalAmount > 0 && touchStyle === 2 && this.data.token) {
      //创建订单
      let createOrderData = await ajax("/SmallAppSmileFundauthPreform", { token: this.data.token, amount: totalAmount }, 'POST');
      if (createOrderData.data.status === 1) {
        console.log('进来了');
        this.setData({ out_trade_no: createOrderData.data.out_trade_no });
        //启动收银台
        my.ix.startApp({
          appName: 'cashier',
          bizNo: createOrderData.data.out_trade_no,
          totalAmount: totalAmount,
          orderDetail: [{ name: '支付', content: '普通商品' }],
          showScanPayResult: true,
          success: async (r) => {
            let parameData = {
              code: r.barCode,
              token: this.data.token,
              out_trade_no: this.data.out_trade_no,
              devices: my.getStorageSync({ key: 'system' }).data,
              ftoken: r.ftoken
            }
            console.log('parameData', parameData)
            //支付接口
            let payResultData = await ajax("/SmallAppSmileFundauth", parameData, 'POST');
            console.log(payResultData)

            //暂时关闭自定义结果页
            my.navigateTo({ url: '../pay-result/pay-result?out_trade_no=' + this.data.out_trade_no + '&result_status=2' });

            if (payResultData.data.status === 1) {
              console.log('支付成功了。。。')
              // 请求打印数据并打印
              this.getData()
              // this.onKeyPress(r)
              my.ix.startApp({
                appName: 'scanPayResult',
                bizNo: this.data.out_trade_no,
                totalAmount: totalAmount,
                success: (r) => {
                  console.log('展示结果页')
                }
              })
            } else {
              my.alert({
                content: payResultData.data.msg
              });
            }
          }
        })
      }
    } else {
      // 语音功能
      my.ix.speech({
        text: '输入金额有误',
        success: (r) => {
          console.log('输入金额有误')
        }
      });
    }
    console.log('aaa')
  },
  // 刷脸预授权
  async sFace() {
    let totalAmount = this.data.totalAmount;
    this.setData({
      totalAmount: 0
    })
    console.log(totalAmount)
    let createOrderData = await ajax("/SmallAppSmileFundauthPreform", { token: this.data.token, amount: totalAmount }, 'POST');
    if (createOrderData.data.status === 1) {
      console.log('进来了');
      this.setData({ out_trade_no: createOrderData.data.out_trade_no });
      // 刷脸核身
      my.ix.faceVerify({
        verifyType: 'idCard',
        option: 'pay',
        needPreAuth: 'true',
        success: async (res) => {
          let ftoken = res.ftoken;
          let parameData = {
            code: ftoken,
            token: this.data.token,
            out_trade_no: this.data.out_trade_no,
            deviceType: 'alipay',
            devices: my.getStorageSync({ key: 'system' }).data
          }
          let payResultData = await ajax("/SmallAppSmileFundauth", parameData, 'POST');
          console.log(payResultData)
          if (payResultData.data.status === 1) {
            //暂时关闭自定义结果页
            console.log('暂时关闭自定义结果页', this.data.out_trade_no, payResultData.data.out_order_no)
            // 预授权订单页result_status=2
            my.navigateTo({ url: '../pay-result/pay-result?out_trade_no=' + payResultData.data.out_order_no + '&result_status=2' });
          }
        }
      })
    }
  },
});
